import { Request, Response } from 'express';
import { CircleComment } from '../models/CircleComment';
import { CirclePost } from '../models/CirclePost';
import { User } from '../models/User';
import { Circle } from '../models/Circle';

// 创建评论
export const createComment = async (req: Request, res: Response): Promise<void> => {
    try {
        const { content, postId, parentId } = req.body;
        const authorId = (req.user as any).id;

        // 检查帖子是否存在
        const post = await CirclePost.findByPk(postId);
        if (!post) {
            res.status(404).json({ message: '帖子不存在' });
            return;
        }

        // 检查是否是圈子成员
        const circle = await Circle.findByPk(post.circleId);
        if (!circle) {
            res.status(404).json({ message: '圈子不存在' });
            return;
        }

        const isMember = await circle.hasMember(authorId);
        if (!isMember) {
            res.status(403).json({ message: '只有圈子成员才能评论' });
            return;
        }

        // 如果是回复评论，检查父评论是否存在
        if (parentId) {
            const parentComment = await CircleComment.findByPk(parentId);
            if (!parentComment) {
                res.status(404).json({ message: '父评论不存在' });
                return;
            }
        }

        // 创建评论
        const comment = await CircleComment.create({
            content,
            authorId,
            postId,
            parentId,
            likeCount: 0
        });

        // 更新帖子评论数
        await post.increment('commentCount');

        // 获取完整的评论信息
        const fullComment = await CircleComment.findByPk(comment.id, {
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                }
            ]
        });

        res.status(201).json(fullComment);
        return;
    } catch (error) {
        console.error('创建评论失败:', error);
        res.status(500).json({ message: '创建评论失败' });
    }
};

// 获取评论列表
export const getComments = async (req: Request, res: Response): Promise<void> => {
    try {
        const { postId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const { count, rows } = await CircleComment.findAndCountAll({
            where: {
                postId,
                parentId: null // 只获取一级评论
            },
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: CircleComment,
                    as: 'replies',
                    include: [
                        {
                            model: User,
                            as: 'author',
                            attributes: ['id', 'username', 'avatar']
                        }
                    ],
                    limit: 3 // 只获取前3条回复
                }
            ],
            limit: Number(limit),
            offset,
            order: [['createdAt', 'DESC']]
        });

        res.json({
            total: count,
            pages: Math.ceil(count / Number(limit)),
            currentPage: Number(page),
            comments: rows
        });
    } catch (error) {
        console.error('获取评论列表失败:', error);
        res.status(500).json({ message: '获取评论列表失败' });
    }
};

// 获取评论回复列表
export const getCommentReplies = async (req: Request, res: Response): Promise<void> => {
    try {
        const { commentId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        const { count, rows } = await CircleComment.findAndCountAll({
            where: {
                parentId: commentId
            },
            include: [
                {
                    model: User,
                    as: 'author',
                    attributes: ['id', 'username', 'avatar']
                }
            ],
            limit: Number(limit),
            offset,
            order: [['createdAt', 'ASC']]
        });

        res.json({
            total: count,
            pages: Math.ceil(count / Number(limit)),
            currentPage: Number(page),
            replies: rows
        });
    } catch (error) {
        console.error('获取评论回复列表失败:', error);
        res.status(500).json({ message: '获取评论回复列表失败' });
    }
};

// 更新评论
export const updateComment = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const { content } = req.body;
        const userId = (req.user as any).id;

        const comment = await CircleComment.findByPk(id);
        if (!comment) {
            res.status(404).json({ message: '评论不存在' });
            return;
        }

        // 检查权限
        if (comment.authorId !== userId) {
            res.status(403).json({ message: '没有权限修改评论' });
            return;
        }

        // 更新评论
        await comment.update({ content });

        res.json(comment);
    } catch (error) {
        console.error('更新评论失败:', error);
        res.status(500).json({ message: '更新评论失败' });
    }
};

// 删除评论
export const deleteComment = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const comment = await CircleComment.findByPk(id);
        if (!comment) {
            res.status(404).json({ message: '评论不存在' });
            return;
        }

        // 检查权限
        if (comment.authorId !== userId) {
            res.status(403).json({ message: '没有权限删除评论' });
            return;
        }

        // 删除评论
        await comment.destroy();

        // 更新帖子评论数
        const post = await CirclePost.findByPk(comment.postId);
        if (post) {
            await post.decrement('commentCount');
        }

        res.json({ message: '评论删除成功' });
    } catch (error) {
        console.error('删除评论失败:', error);
        res.status(500).json({ message: '删除评论失败' });
    }
};

// 点赞评论
export const likeComment = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const comment = await CircleComment.findByPk(id);
        if (!comment) {
            res.status(404).json({ message: '评论不存在' });
            return;
        }

        // 检查是否已经点赞
        const hasLiked = await comment.hasLike(userId);
        if (hasLiked) {
            res.status(400).json({ message: '已经点赞过该评论' });
            return;
        }

        // 添加点赞
        await comment.addLike(userId);
        await comment.increment('likeCount');

        res.json({ message: '点赞成功' });
    } catch (error) {
        console.error('点赞评论失败:', error);
        res.status(500).json({ message: '点赞评论失败' });
    }
};

// 取消点赞评论
export const unlikeComment = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.params;
        const userId = (req.user as any).id;

        const comment = await CircleComment.findByPk(id);
        if (!comment) {
            res.status(404).json({ message: '评论不存在' });
            return;
        }

        // 检查是否已经点赞
        const hasLiked = await comment.hasLike(userId);
        if (!hasLiked) {
            res.status(400).json({ message: '还没有点赞该评论' });
            return;
        }

        // 取消点赞
        await comment.removeLike(userId);
        await comment.decrement('likeCount');

        res.json({ message: '取消点赞成功' });
    } catch (error) {
        console.error('取消点赞评论失败:', error);
        res.status(500).json({ message: '取消点赞评论失败' });
    }
}; 